# -*- coding: utf-8 -*-

from odoo import models, fields, api
from mapper import Mapper
from http_exporter import HttpExporter
from dateutil import parser
from calendar import timegm


class Customer(models.Model, Mapper):
    _name = 'ptengine.customer'
    _inherits = {'res.partner': 'partner_id'}
    _inherit = ['mail.thread']

    exportFields = {
        'user_name': ('account_nickname', True),
        'ptengine_astrict_ids' : ('astrictConfBeanList', True),
        'package_end_time':('packageEndTime', False),
        'package_id': ('packageId', False)
    }

    fieldsMapping = {
        'email': 'account',
        'create_time': 'register_date',
        'lastlogintime': 'last_login_time'
    }

    partner_id = fields.Many2one('res.partner', 'Partner')
    package_id = fields.Many2one('ptengine.package', 'Package', track_visibility='onchange')
    ptengine_astrict_ids = fields.One2many('ptengine.customer.astrict', 'customer_id', 'Astrict list')

    uid = fields.Char('Account Id')
    account = fields.Char('Account')
    register_date = fields.Datetime('Register Date')
    last_login_time = fields.Datetime('Last Login Time')
    login_times = fields.Integer('Login Times')
    source_detail = fields.Char('Partner Code')
    fee = fields.Float('Fee', track_visibility='onchange')
    package_end_time = fields.Datetime('End Time', track_visibility='onchange')
    source = fields.Selection([(0, 'PtWebsite'),
                               (1, 'Internal'),
                               (2, 'Collaborator'),
                               (3, 'Promotions'),
                               (4, 'Affiliate'),
                               (5, 'WpPlugin'),
                               (6, 'Referral'),
                               (7, 'Blog'),
                               (8, 'SP'),
                               (9, 'ChinaPtWebsite')], 'Source')

    user_name = fields.Char('User Name')

    package_name = fields.Char(related='package_id.name')

    @api.onchange('package_id')
    def _onchange_package(self):
        if self.package_id.package_id == '100009':
            return

        self.fee = self.package_id.list_price

    @api.model
    def updateAstrict(self, pUid, pAid, consumption, ceiling):
        customerAstrict = self.env['ptengine.customer.astrict'].search([('customer_id.uid', '=', pUid),
                                                                    ('astrict_id.astrict_id', '=', pAid)])[0]

        customerAstrict.write({'ceiling': ceiling, 'consumption': consumption})
        return True

    @api.model
    def updateAstricts(self, pUid, vals):
        for astrict in vals:
            self.updateAstrict(pUid, astrict[0], astrict[1], astrict[2])
        return True

    @api.model
    def updateField(self, pUid, vals):
        customer = self.search([('uid', '=', pUid)])[0]
        super(Customer, customer).write(dict((self.getMappingField(k), v) for k, v in vals.items()))
        return True

    @api.model
    def changePackage(self, pUid, pPackageId):
        customer = self.env['ptengine.customer'].search([('uid', '=', pUid)])[0]
        package = self.env['ptengine.package'].search([('package_id', '=', pPackageId)])[0]

        customer.write({'package_id': package.id})
        return True

    @api.model
    def createCustomer(self, vals):
        pPackageId = vals['package_id']
        package = self.env['ptengine.package'].search([('package_id', '=', pPackageId)])[0]
        self.create(dict((self.getMappingField(k), package.id if k == 'package_id' else v) for k, v in vals.items()))

        return True

    def getExportValue(self, k, v):
        if k == 'package_id':
            package = self.env['ptengine.package'].browse(v)
            return package.package_id
        else:
            return v

    def getExportConstraint(self, tableName):
        return {'uid': self.uid}

    @api.model
    def create(self, vals):
        new_record = super(Customer, self).create(vals)

        new_record.write({"ptengine_astrict_ids": [(0,0,{"astrict_id": astrict.id}) for astrict in self.env['ptengine.astrict'].search([])]})
        new_record.updatePackageAstrict()

        return new_record

    @api.multi
    def write(self, vals):
        if not self.isFromImporter():
            export = HttpExporter(self.env['ir.config_parameter'])
            export.Export(self, vals)

        super(Customer, self).write(vals)

        if vals.has_key('package_id'):
            self.updatePackageAstrict()

        return True

    def updatePackageAstrict(self):
        if self.package_id.package_id == '100009':
            return
        super(Customer, self).write({'fee': self.package_id.list_price})

        for packageAstrict in self.env['ptengine.package.astrict'].search([('package_id.id', '=', self.package_id.id)]):
            customerAstrict = self.ptengine_astrict_ids.filtered(lambda r: r.astrict_id.id == packageAstrict.astrict_id.id)[0]
            customerAstrict.write({'ceiling': packageAstrict.ceiling})

    def getExportInfo(self, vals):
        result = {}

        for k, v in vals.items():
            if k in self.exportFields:
                exportName = self.exportFields[k][0]
                if k == 'ptengine_astrict_ids':
                    result[exportName] = self.getAstrictExportObject(v)
                elif k == 'package_end_time':
                    '''convert time'''
                    result[exportName] = timegm(parser.parse(v).utctimetuple()) * 1000
                elif k == 'package_id':
                    result[exportName] = int(self.package_id.package_id)
                elif self.exportFields[k][1]:
                    result.setdefault('infoList', []).append({'field': exportName, 'value': v})
                else:
                    result[exportName] = v

        if len(result) > 0 :
            result['uid'] = int(self.uid)

        return 'userInfo', result

    def getAstrictExportObject(self, vals):
        return [{'asctrictId': self.ptengine_astrict_ids.browse(astrict[1]).astrict_id.astrict_id, 'ceiling':astrict[2]['ceiling']} for astrict in vals if astrict[2] != False]


class Package(models.Model):
    _name = 'ptengine.package'

    _inherits = {'product.template': 'product_id'}
    product_id = fields.Many2one('product.template', 'Product', readonly = True)
    package_id = fields.Char('Package Id')
    ptengine_astrict_ids = fields.One2many('ptengine.package.astrict', 'package_id', 'Astrict list')


    @api.model
    def create(self, vals):
        new_record = super(Package, self).create(vals)
        new_record.type = 'service'
        return new_record


class Customer_Astrict(models.Model, Mapper):
    _name = 'ptengine.customer.astrict'
    customer_id = fields.Many2one('ptengine.customer', 'Customer')
    astrict_id = fields.Many2one('ptengine.astrict', 'Astrict Name')
    ceiling = fields.Float('Ceiling', (20, 0))
    consumption = fields.Float('Usage', (20, 0))

    exportFields = {'ceiling' :('ptengine_user_astrict_conf', 'ceiling'),
                     'consumption' : ('ptengine_user_astrict_conf', 'consumption')}

    def getExportConstraint(self, tableName):
        return {'uid': self.customer_id.uid, 'astrict_id': self.astrict_id.astrict_id}


class Astrict(models.Model):
    _name = 'ptengine.astrict'
    name = fields.Char('Name')
    astrict_id = fields.Integer('Id')


class Package_Astrict(models.Model):
    _name = 'ptengine.package.astrict'
    package_id = fields.Many2one('ptengine.package', 'Package Name')
    astrict_id = fields.Many2one('ptengine.astrict', 'Astrict Name')
    ceiling = fields.Float('Ceiling', (20, 0))